<template>
  <div class="download">
    <div class="content">
      <div class="logo">
        <img :src="assets.logo" alt />
      </div>
      <div class="title">
        <img :src="assets.title" alt />
      </div>
      <div v-if="assets">
        <div
          class="btn"
          @click="download(item)"
          v-for="item in assets.downloadButtons"
          :key="item.type"
        >
          <img :src="item.image" alt />
        </div>
      </div>
      <div class="image">
        <img :src="assets.card" alt />
      </div>
      <NuxtLink :to="$i18n.path('m')">
        <div class="to-index">{{ assets.indexText }}</div>
      </NuxtLink>
    </div>
    <div class="bg" v-if="isAndroid && isWeixin">
      <div class="tips" v-html="$t('wechat_Open_in_Browser')"></div>
    </div>
    <div class="Twitter-bg" v-if="isAndroid && isTwitter">
      <div class="tips">{{ $t('Twitter_Open_in_Browser') }}</div>
    </div>
  </div>
</template>

<script>
import { Collect } from '@/utils/collect';
import { LRUcache } from '@/utils/lru_cache.js';

const APP_ID = 'com.tnaot.newspro';
const GOOGLE_PLAY_URL = `https://play.google.com/store/apps/details?id=${APP_ID}`;
const GOOGLE_PLAY_SCHEME_URL = `market://details?id=${APP_ID}`;
const APPLE_STORE_URL = 'https://itunes.apple.com/us/app/tnaot/id1296073079';

const DOWNLOAD_TYPES = {
  APPLE: 'apple',
  GOOGLE: 'google',
  LOCAL: 'local'
};

const ASSETS = {
  zh: {
    logo: require('~/assets/img/en_logo@2x.png'),
    title: require('~/assets/img/zh_title@2x.png'),
    downloadButtons: [
      {
        type: DOWNLOAD_TYPES.APPLE,
        image: require('~/assets/img/apple_store_download_cn.png'),
        url: APPLE_STORE_URL
      },
      {
        type: DOWNLOAD_TYPES.GOOGLE,
        image: require('~/assets/img/google_play_download_cn.png'),
        url: GOOGLE_PLAY_URL,
        schemeURL: GOOGLE_PLAY_SCHEME_URL
      },
      {
        type: DOWNLOAD_TYPES.LOCAL,
        image: require('~/assets/img/local_download_cn.png')
      }
    ],
    card: require('~/assets/img/img_cn@2x.png'),
    indexText: '进入网页'
  },
  km: {
    logo: require('~/assets/img/en_logo@2x.png'),
    title: require('~/assets/img/km_title@2x.png'),
    downloadButtons: [
      {
        type: DOWNLOAD_TYPES.APPLE,
        image: require('~/assets/img/apple_store_download_km.png'),
        url: APPLE_STORE_URL
      },
      {
        type: DOWNLOAD_TYPES.GOOGLE,
        image: require('~/assets/img/google_play_download_km.png'),
        url: GOOGLE_PLAY_URL,
        schemeURL: GOOGLE_PLAY_SCHEME_URL
      },
      {
        type: DOWNLOAD_TYPES.LOCAL,
        image: require('~/assets/img/local_download_km.png')
      }
    ],
    card: require('~/assets/img/img_kh@2x.png'),
    indexText: 'ចូលទំព័រដើម'
  }
};

function getAssets(locale, { isAndroid }) {
  const filterButtons = bs => {
    if (isAndroid) {
      return bs.filter(t => t.type !== DOWNLOAD_TYPES.APPLE);
    }
    return bs.filter(t => t.type === DOWNLOAD_TYPES.APPLE);
  };
  const assets = locale === 'zh' ? ASSETS.zh : ASSETS.km;
  return {
    ...assets,
    downloadButtons: filterButtons(assets.downloadButtons)
  };
}

const isAndroidClient = s => /Android/i.test(s) || /Adr/i.test(s);
const isIosClient = s => /\(i[^;]+;( U;)? CPU.+Mac OS X/i.test(s);
const isTwitterClient = s => /Twitter/i.test(s);
const isWeChatClient = s => /microMessenger/i.test(s);

export default {
  data() {
    return {
      isAndroid: false,
      isTwitter: false,
      isiOS: false,
      isWeixin: false,
      assets: {},
      apkDownloadUrl: '', //安卓下载1,
      fastestAndroidDownloadUrl: ''
    };
  },
  head() {
    /* 动态配置title,meta，便于facebook爬虫 */
    return {
      title: this.$t('tnaot_title'),
      meta: [
        { name: 'keywords', content: this.$t('indexKeywords') },
        { name: 'description', content: this.$t('indexDescription') },
        {
          property: 'og:image',
          content: 'https://m.tnaot.com/img/logo-256.png'
        },
        { property: 'og:title', content: this.$t('tnaot_title') },
        { property: 'og:type', content: 'website' },
        { property: 'fb:app_id', content: '1756001284709028' },
        { property: 'twitter:title', content: this.$t('tnaot_title') },
        {
          property: 'twitter:image:src',
          content: 'https://m.tnaot.com/img/logo-256.png'
        },
        {
          property: 'twitter:image',
          content: 'https://m.tnaot.com/img/logo-256.png'
        }
      ]
    };
  },

  /* 服务端异步请求数据 */
  async asyncData(ctx) {
    const cacheKey = '/download/app/android';
    let result = LRUcache.get(cacheKey);

    try {
      if (!result) {
        result = await ctx.$axios.$get(`/download/app/android`);
        LRUcache.set(cacheKey, result);
      }
    } catch (err) {
      console.log(err);
      ctx.error({ statusCode: 404, message: '网络异常，请重试！' });
    }

    if (!result) {
      return ctx.error({ statusCode: 404, message: 'Post not found' });
    }

    const userAgent = process.server
      ? ctx.req.headers['user-agent']
      : window.navigator.userAgent;
    const isAndroid = isAndroidClient(userAgent);

    return {
      isAndroid,
      assets: getAssets(ctx.app.i18n.locale, { isAndroid }),
      isiOS: isIosClient(userAgent),
      isTwitter: isTwitterClient(userAgent),
      isWeixin: isWeChatClient(userAgent),
      apkDownloadUrl: result
    };
  },
  mounted() {
    this.setFastestDownloadUrl();
    this.collect('/download', 8);
  },

  methods: {
    async setFastestDownloadUrl() {
      const image = 'https://apk.tnaot.com/apk/logo.png';
      const downloadUrl = this.apkDownloadUrl;
      const replace = url =>
        url.replace(/^(https?:\/\/)?([^\.]+)([^\/]+)/, '$1$21$3');
      const imageB = replace(image);
      const result = await this.getFastestImageUrl(image, imageB);
      this.fastestAndroidDownloadUrl =
        result === imageB ? replace(downloadUrl) : downloadUrl;
    },

    getFastestImageUrl(...srcList) {
      let resolved = false;
      let errorCounter = 0;
      return new Promise((resolve, reject) => {
        srcList.forEach(src => {
          const img = new Image();
          img.onload = () => {
            if (resolved) return;
            resolved = true;
            resolve(src);
          };
          img.onerror = error => {
            errorCounter += 1;
            if (errorCounter === srcList.length) reject('all src failed');
          };
          img.src = src;
        });
      });
    },

    async download(type) {
      // 埋点
      this.collect('/download', 1);

      switch (type.type) {
        case DOWNLOAD_TYPES.LOCAL:
          window.location.href =
            this.fastestAndroidDownloadUrl || this.apkDownloadUrl;
          break;
        case DOWNLOAD_TYPES.GOOGLE:
          this.jumpOrDownload(type.schemeURL, type.url);
          break;
        case DOWNLOAD_TYPES.APPLE:
          window.location.href = type.url;
      }
    },

    //埋点
    async collect(path = '', action) {
      const { flag } = this.$route.query;
      if (flag) {
        Collect(
          action,
          '渠道下载页' + path,
          'flag=' + flag,
          this.$i18n.locale === 'zh' ? 1 : 2
        );
      } else {
        Collect(
          action,
          'H5下载页' + path,
          'channel=',
          this.$i18n.locale === 'zh' ? 1 : 2
        );
      }
    },

    // 打开 Scheme 应用商店 下载链接
    jumpOrDownload(jumpScheme, downloadUrl) {
      if (process.client) {
        let timer = null;
        document.addEventListener('visibilitychange', function () {
          var tag = document.hidden || document.webkitHidden;
          if (tag) {
            clearTimeout(timer);
          }
        });
        document.addEventListener('webkitvisibilitychange', function () {
          var tag = document.hidden || document.webkitHidden;
          if (tag) {
            clearTimeout(timer);
          }
        });
        document
          .querySelector('body')
          .addEventListener('pagehide', function () {
            clearTimeout(timer);
          });
        timer = setTimeout(function () {
          window.location.href = downloadUrl;
        }, 1000);
        window.location.href = jumpScheme;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.download {
  font-size: 50px;
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  overflow-y: auto;
  .content {
    width: 100%;
    /* height: 100%; */
    position: absolute;
    top: 10.5%;
    background: #fff;
  }

  img {
    width: 100%;
  }

  .logo {
    width: 220px;
    height: 52px;
    margin: 0 auto 0;
  }

  .title {
    width: 692px;
    height: 68px;
    margin: 32px auto 0;
  }

  .btn {
    width: 320px;
    height: 80px;
    margin: 20px auto 0;
  }

  .image {
    width: 538px;
    height: 538px;
    margin: 62px auto 0;
  }
  .bg,
  .Twitter-bg {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 99;
    // display: none;
  }
  .Twitter-bg .tips {
    font-size: 44px;
    color: #fff;
    font-weight: bolder;
    text-align: center;
    position: absolute;
    bottom: 100px;
    left: 50%;
    transform: translateX(-50%);
  }
  .bg .tips {
    font-size: 36px;
    height: 120px;
    color: #fff;
    font-weight: bolder;
    padding-top: 100px;
    text-align: center;
    padding-left: 30px;
    background: url('~assets/img/alert-arrow.png') no-repeat 90% 10%;
    background-size: 58px 72px;
  }
  .to-index {
    font-size: 24px;
    text-align: center;
    margin: 20px auto 0;
    color: rgba(12, 12, 28, 1);
    height: 48px;
    line-height: 48px;
    border-radius: 28px;
    border: 2px solid rgba(12, 12, 28, 0.2);
    width: 144px;
    padding: 0 24px;
  }
}
</style>
